package dahuiji.regist.servlet;

import javax.servlet.RequestDispatcher;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dahuiji.common.entity.User;
import dahuiji.common.servlet.BaceServlet;
import dahuiji.common.util.EncodingFormat;
import dahuiji.regist.service.RegistService;

/**
 * Servlet implementation class RegistServlet
 */
public class RegistServlet extends BaceServlet {
	private static final long serialVersionUID = 1L;
	Logger log = Logger.getLogger(RegistServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String result = null;// 注册失败后的提示
		String nextPage = null;// 跳转页面
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String codeinput = request.getParameter("vf");
		HttpSession session = request.getSession();
		String code = (String) session.getAttribute("verifycode");
		RegistService registService = null;
		RequestDispatcher rd;
		if (name == null || name.equals("")) {
			result = "用户名不能为空";
			nextPage = "/view/regist/regist.jsp";
			request.setAttribute("msg", result);

		} else if (email == null || email.equals("")) {
			result = "邮箱不能为空";
			nextPage = "/view/regist/regist.jsp";
			request.setAttribute("msg", result);

		} else if (password == null || password.equals("")) {
			result = "密码不能为空";
			nextPage = "/view/regist/regist.jsp";
			request.setAttribute("msg", result);

		} else if(!codeinput.equals(code)){
			result = "验证码不对";
			nextPage = "/view/regist/regist.jsp";
			request.setAttribute("msg", result);
		}else{
			log.info("注册");
			User user = new User(name, password, email);
			registService = new RegistService();
			registService.save(user);
			nextPage = "/view/index.jsp";// 注册后跳转到首页
			session.putValue("user", user);
		}

		rd = getServletContext().getRequestDispatcher(nextPage);
		rd.forward(request, response);

		return nextPage;

	}

}
